package com.jd.org.service.impl;

import com.jd.basic.domain.BaseDomain;
import com.jd.basic.query.BaseQuery;
import com.jd.basic.util.BaiduAuditUtils;
import com.jd.basic.util.BusinessException;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.domain.ShopAuditLog;
import com.jd.org.dto.ShopAdminDto;
import com.jd.org.dto.ShopAuditDto;
import com.jd.org.dto.ShopSettlementDto;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.mapper.ShopAuditLogMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.org.service.IShopService;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.org.vo.ShopPageVo;
import com.jd.sys.domain.Role;
import com.jd.sys.mapper.RoleMapper;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shaqian
 * @since 2023-02-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper auditMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void settlement(ShopSettlementDto dto) {
        // todo 邮箱验证 手机验证

        System.err.println("进入service层" + dto);
        // 参数校验
        // 1.店铺名称是否存在
        if (null != shopMapper.findByName(dto.getName())){
            throw new BusinessException("店铺名称已存在 请重新输入！");
        }
        // 2.手机号合法性
        ShopAdminDto admin = dto.getAdmin();
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$"); // 验证手机号
        Matcher matcher = pattern.matcher(admin.getPhone());
        if (!matcher.matches()){
            throw new BusinessException("用户手机号格式不正确！");
        }
        // 3.校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码不一致！");
        }
        // 4.判断当前管理员是否已经管理了店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (null != employee && null != employee.getShopId()){
            throw new BusinessException("该员工已经管理了一个店铺 请重新输入！");
        }
        if (!BaiduAuditUtils.TextCensor(dto.getName())){
            throw new BusinessException("店铺名称不合法 请重新输入!");
        }
        if (!BaiduAuditUtils.ImgCensor(dto.getLogo())){
            throw new BusinessException("店铺Logo违规 请重新上传!");
        }
        Logininfo logininfo = new Logininfo();

        // 保存信息 更新shop和emp表
        Shop shop = dto.getShop();
        shopMapper.add(shop);
        System.err.println("ssssssssssss"+shop);
        Employee emp = dto.getEmp();
        emp.setShopId(shop.getId());
        BeanUtils.copyProperties(emp,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);
        emp.setLogininfoId(logininfo.getId());
        employeeMapper.add(emp);
        Shop shop1 = new Shop();
        shop1.setId(shop.getId());
        shop1.setAdminId(emp.getId());
        shop1.setState(0);
        shopMapper.update(shop1);
        shopMapper.addEmpAndRole(emp.getId(),24L);

    }

    @Override
    public void auditPass(ShopAuditDto dto) {
        // 参数校验
        Shop shop = new Shop();
        if (dto!=null){
            System.err.println("实现类" + dto);
            // 参数校验
            if (null != dto.getShopId()){
                shop.setId(dto.getShopId());
                shop.setState(1);
                shopMapper.update(shop);
            }
            ShopAuditLog shopAuditLog = new ShopAuditLog();
            shopAuditLog.setShopId(dto.getShopId());
            shopAuditLog.setAuditTime(new Date());
            shopAuditLog.setNote(dto.getNote());
            shopAuditLog.setAuditId(1);
            auditMapper.add(shopAuditLog);
//            try {
//                // 1.创建复杂邮件对象
//                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//                // 2.发送复杂邮件的工具类
//                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//                helper.setFrom("443237572@qq.com");
//                helper.setSubject("测试复杂邮件");
//                // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//                helper.setText("<h1>恭喜您入驻成功 请点击下方链接前往手动激活店铺</h1>"+
//                        "http://localhost:80/#/activity/",true);
//                // 4.添加附件
//                helper.addAttachment("好东西.jpg",new File("E:\\feiqiu\\feiq\\RecvFace\\0bbfea4f.bmp"));
//                // 5.设置收件人
//                helper.setTo("443237572@qq.com");
//                // 6.发送邮件
//                javaMailSender.send(mimeMessage);
//            } catch (MessagingException e) {
//                e.printStackTrace();
//            }
        }
    }

    @Override
    public Shop auditReject(ShopAuditDto dto) {
        Shop byId = shopMapper.findById(dto.getShopId());
        byId.setState(3);
        shopMapper.update(byId);
        System.err.println(byId);
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("2621512196@qq.com");
            helper.setSubject("测试复杂邮件");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>入驻失败 审核未通过 点击下方链接重新填写信息</h1>" +
                    "http://localhost:8081/#/activity?" + dto.getShopId(), true);
            // 4.添加附件
//            helper.addAttachment("好东西.jpg", new File("E:\\feiqiu\\feiq\\RecvFace\\0bbfea4f.bmp"));
            // 5.设置收件人
            helper.setTo("2621512196@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setShopId(dto.getShopId());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setNote(dto.getNote());
        shopAuditLog.setAuditId(1);
        auditMapper.add(shopAuditLog);
        return byId;
    }

    @Override
    public void auditRejectUpdate(Shop shop) {
        shop.setState(0);
        shopMapper.update(shop);
    }

    @Override
    public int insertList(List<Shop> list) {
        return shopMapper.insertList(list);
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        Integer totals = shopMapper.queryByCount(query);
        if (0 >= totals){
            return new PageList<>(0,new ArrayList<>());
        }
        List<Shop> rows = shopMapper.queryByPage(query);
//        rows.stream().collect(Collectors.toMap(BaseDomain::getId, s->s));
        Map<Long, Shop> map = rows.stream().collect(Collectors.toMap(BaseDomain::getId, new Function<Shop, Shop>() {
            @Override
            public Shop apply(Shop shop) {
                return shop;
            }
        }));

        auditMapper.findAll().stream()
                .filter(s -> null != map.get(s.getShopId()))
                .forEach(s1 -> map.get(s1.getShopId()).getAuditLogs().add(s1));
        System.err.println("MMMMMMMMMMMMMMMMM" + map);


        return new PageList<>(totals,rows);
// 套路：
        // 先获取到父级的集合
// 根据父级的id集合查询出来所有的子级集合
// 将子级集合根据父级的id进行分组 转成map
// 遍历父级集合 使用map.get(父级的id)
// 将子级放入到父级

////查询总条数
//        Integer integer = shopMapper.queryByCount(query);
//        //查询数据
//        List<ShopPageVo> shops = auditMapper.shopQueryByPage(query);
//        Map<Long, ShopPageVo> collect = shops.stream().collect(Collectors.toMap(ShopPageVo::getId, s -> s));
//        //key id  vlues 返回实体
//        List<Long> shopIds = shops.stream().map(s -> s.getId()).collect(Collectors.toList());
//        auditMapper.findShopIds(shopIds).stream()
//                .forEach(s1 -> collect.get(s1.getShopId()).getAuditLogs().add(s1));
//        PageList<ShopPageVo> PageList = new PageList<>();
//        PageList.setRows(shops);
//        PageList.setTotals(integer);
//        return PageList;
    }
}

